package com.itheima.filter;

import com.alibaba.fastjson.JSONObject;
import com.itheima.pojo.Result;
import com.itheima.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author wuJiaWei
 * @version 1.0
 */
//@WebFilter(urlPatterns = "/*") // 拦截所有请求
@Slf4j
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 1.获取请求路径
        String url = request.getRequestURL().toString();
        log.info("请求的url: {}", url);
        // 2.判断是否包含login
        if (url.contains("login")) {
            log.info("登录操作，放行");
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        // 3.获取token
        String jwtToken =  request.getHeader("token");
        // 4.判断token是否存在
        if (!StringUtils.hasLength(jwtToken)) {
            log.info("请求头token为空，拦截");
            Result error = Result.error("NOT_LOGIN");
            String notLogin = JSONObject.toJSONString(error);// 将error转换为json
            response.getWriter().write(notLogin);
            return;
        }
        // 5.判断token是否正确
        try {
            JwtUtils.parseJWT(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析失败，拦截");
            Result error = Result.error("NOT_LOGIN");
            String notLogin = JSONObject.toJSONString(error);// 将error转换为json
            response.getWriter().write(notLogin);
            return;
        }
        // 6.放行
        filterChain.doFilter(servletRequest, servletResponse);
        // 7.放行成功
        log.info("放行成功");
    }
}
